package xml;

import chess.Piece;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class ChessWriter {
	
	public static void write(String file, Piece[] pieces) {
		try {
			//char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
			
			XMLStreamWriter xmlStreamWriter = null;
			Writer target = new FileWriter(file);
			XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
			xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(target);
			xmlStreamWriter.writeStartDocument();
			
			// start root
			xmlStreamWriter.writeStartElement("chessboard");
			
			for (int i = 0; i < pieces.length; i++) {
				xmlStreamWriter.writeStartElement("piece");
				{
					//xmlStreamWriter.writeAttribute("x", String.valueOf(letters[pieces[i].getX() - 1]));
					xmlStreamWriter.writeAttribute("x", String.valueOf((char) (pieces[i].getX() + 'A' - 1)));
					xmlStreamWriter.writeAttribute("y", String.valueOf(pieces[i].getY()));
					xmlStreamWriter.writeAttribute("white", String.valueOf(pieces[i].isWhite()));
					xmlStreamWriter.writeAttribute("type", pieces[i].getType());
				}
				xmlStreamWriter.writeEndElement();
			}
				
			// finish root
			xmlStreamWriter.writeEndElement();

			// finish doc
			xmlStreamWriter.writeEndDocument();
			xmlStreamWriter.flush();
			xmlStreamWriter.close();
		} catch (XMLStreamException | IOException e) {
			System.out.println(e.getMessage());
		}
	}
}